//
//  BleSearchViewController.m
//  Lightthings
//
//  Created by Hero on 2024/11/20.
//

#import "BleSearchViewController.h"
#import "BleSearchModel.h"
#import <KLToast/ZHToast.h>
#import "aes.h"
@interface BleSearchViewController ()<FRQBluetoothManagerDelegate>
/* <#note#> */
@property (nonatomic, strong) MainSectionModel * s1, * s2;

@property (nonatomic, strong) NSMutableArray<CBPeripheral *> * ScanDataArr;
/* <#note#> */
@property (nonatomic, strong) NSArray * secretArr;
@end

@implementation BleSearchViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.jy_title = SWString(@"自动搜索附近设备");
    
    [[FRQBluetoothManager shareManager] addBleDelegate:self];
    
    [JYInitializer jy_initLabelWithText:SWString(@"自动搜索附近设备") textColor:KLColor(@"666666") font:U_font(16) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(20);
        kMakeHV(20);
        kMakeTV(self.jy_bar_h + 5);
    }];
    
    self.collectionInsets = kEdge(self.jy_bar_h + 30, 0, klSafeAreaEdgeInsets.bottom, 0);

    MainSectionModel * s = [[MainSectionModel alloc] init];
    [s sectionInsets:kEdge(10, 10, 10, 10) ls:10 is:10];
    s.layoutAlignLeft = YES;
    _s1 = s;
    
    self.dataSources = @[s];
    
    NSArray * arr = [[FRQBluetoothManager shareManager] scanPhoneConnectPeripherals];
    [self.ScanDataArr addObjectsFromArray:arr];
    [self updateUI];
//    DDLogDebug(@"获取已连接的设备 数量 %d",(int)[arr count]);
    
    [self startScan];

//    NSArray * uuidArr = [[NSUserDefaults standardUserDefaults] valueForKey:@"lastconnectuuid"];
    
//    for (CBPeripheral* peripheral in arr)
//    {
//        if ([uuidArr containsObject:peripheral.identifier.UUIDString] && peripheral.state == CBPeripheralStateDisconnected) {
//            self.peripheral = peripheral;
//            dispatch_async(dispatch_get_main_queue(), ^{
//                MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
//                if (!progressHUD) {
//                    progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//                }
//                progressHUD.label.text = SWString(@"正在连接...");
//                progressHUD.mode = MBProgressHUDModeText;
//                [[FRQBluetoothManager shareManager] connectToPeripheral:self.peripheral];
//            });
//        }
//    }
    
    // Do any additional setup after loading the view.
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[FRQBluetoothManager shareManager] removeBleDelegate:self];
}

- (void)startScan {
    [[FRQBluetoothManager shareManager] scanPeripherals];
}

- (void)updateUI {
    [self.s1.items removeAllObjects];
    for (int i = 0; i < self.ScanDataArr.count; i++) {
        CBPeripheral * per = self.ScanDataArr[i];
        BleSearchModel * m = [[BleSearchModel alloc] init];
        m.per = per;
        m.action = kMsgPackForward(@"clickItem:", WKProxy(self), m);
        [self.s1.items addObject:m];
    }
    [self reloadIfNeeded];
}

- (void)clickItem:(BleSearchModel *)model {
    MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
    if (!progressHUD) {
        progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    progressHUD.label.text = SWString(@"正在连接...");
    progressHUD.mode = MBProgressHUDModeText;
    [[FRQBluetoothManager shareManager] cancelScan];
    [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:model.per];
}

#pragma mark -- FRQBluetoothManagerDelegate
-(void)onBLEManagerDiscoverPeripheral:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral advertisement:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    BOOL ha = NO;
    for (CBPeripheral * per in self.ScanDataArr) {
        if ([peripheral.identifier.UUIDString isEqualToString:per.identifier.UUIDString]) {
            ha = YES;
        }
    }
    if (!ha) {
        [self.ScanDataArr addObject:peripheral];
        [self updateUI];
    }
}

- (void)onBLEManagerDisconnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    [self reloadIfNeeded];
}

-(void)onBLEManagerConnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    DDLogDebug(@"连接成功");
    [self reloadIfNeeded];
}


- (void)onBLEManagerReady:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    // 先握手，再发绑定-》读取功能列表-》设备信息-》其他数据交互
    if (peripheral.deviceType.intValue == BleDevice_Pillow) {
        [PillowCommandTool.sharedInstance updateDateAndTimeCallBack:^(NSString * data) {
                    
        } RealTimeData:NO StopSwith:NO ToPeripheral:peripheral];
        
    }else if (peripheral.deviceType.intValue == BleDevice_Watch) {
        [self handshakeWithPer:peripheral];
    }else  {
        peripheral.deviceType = @(BleDevice_Watch);
        [self handshakeWithPer:peripheral];
    }
}

- (void)handshakeWithPer:(CBPeripheral *)peripheral {

    unsigned char mac[16] ;
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    for (int i = 0; i < 16; i ++) {
        int a = arc4random() % 256;
        char charValue = (char)a;
        mac[i] = charValue;
    }
    DDLogDebug(@"加密前 %@", [NSData dataWithBytes:mac length:sizeof(mac)]);
    self.secretArr = [self convertDataToArray:[NSData dataWithBytes:mac length:sizeof(mac)]];
    Cipher(mac);
    DDLogDebug(@"加密后 %@", [NSData dataWithBytes:mac length:sizeof(mac)]);
//    NSArray * arraaa = [self convertDataToArray:[NSData dataWithBytes:mac length:sizeof(mac)]];
//    LEEAlert.alert.config
//        .LeeContent(@"加密前")
//        .LeeContent([self.secretArr componentsJoinedByString:@""])
//        .LeeContent(@"加密后")
//    .LeeContent([arraaa componentsJoinedByString:@""])
//   
//    .LeeAction(@"关闭", ^{
//        
//    }).LeeShow();
    
//    InvCipher(mac);
//    NSLog(@"%@", [NSData dataWithBytes:mac length:sizeof(mac)]);
//    NSArray * lsit = [self convertDataToArray:[NSData dataWithBytes:mac length:sizeof(mac)]];
//    NSLog(@"%@",lsit);
    for (int i = 0; i < 16; i++) {
        NSNumber * num = [NSNumber numberWithUnsignedChar:mac[i]];
        [arr addObject:num];
    }
    DDLogDebug(@"第一步：开始握手");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance  writeStormCommand:Command_Handshake ToPeripheral:peripheral Value:arr reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (backData.length) {
            NSString * value = [backData substringWithRange:NSMakeRange(26, 32)];
            toast(value);
            if ([value isEqualToString:[self.secretArr componentsJoinedByString:@""]]) {
                toast(@"握手成功");
                [self bindWithPer:peripheral];
            }else{
                
                [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:peripheral];
                toast(@"握手失败，断开链接");
            }
        }
        
    }];
}

- (void)bindWithPer:(CBPeripheral *)peripheral {
    DDLogDebug(@"第二步：开始绑定");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance  writeStormCommand:Command_Bind ToPeripheral:peripheral Value:@[@(1 & 0xff),@(1 & 0xff),@(1 & 0xff),@(1 & 0xff)] reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (backData.length) {
            [self getChipInfo:peripheral];
        }else {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:peripheral];
            toast(@"绑定失败，断开链接");
        }
    }];
}

- (void)getChipInfo:(CBPeripheral *)peripheral {
    DDLogDebug(@"第三步：读取芯片信息");
    [WatchCommandTool.sharedInstance writeStormCommand:Command_ChipInfo ToPeripheral:peripheral Value:@[] reBack:^(NSString * _Nonnull backData) {
        if (backData.length) {
            ///  54590101800174000d00020009000001465238303038
            peripheral.chipInfo = [backData substringFromIndex:26];
            [self getFounctionsWithPer:peripheral];
        }else {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:peripheral];
            toast(@"绑定失败，断开链接");
        }
    }];
}


- (void)getFounctionsWithPer:(CBPeripheral *)peripheral {
    DDLogDebug(@"第四步：获取功能列表");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance  writeStormCommand:Command_FounctionList ToPeripheral:peripheral Value:nil reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (backData.length) {
            NSString * valueStr = [backData substringFromIndex:26];
            NSMutableArray * list= [[NSMutableArray alloc] init];
            for (int i = 1; i < 6; i++) {
                NSString * s1 = [NSString stringWithFormat:@"%lld",strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(2 * i, 2)]] UTF8String], 0, 16)];
                NSString *byte1 = [SWTool decimalToBinary:s1];
                
                for (int j = 7; j >= 0; j --) {
                    BOOL b =  [[byte1 substringWithRange:NSMakeRange(j, 1)] isEqualToString:@"1"];
                    [list addObject:@(b)];
                }
            }

            peripheral.founctionlist = list;
            
            [self getDeviceInfo:peripheral];
            
        }else {
            [self getDeviceInfo:peripheral];
        }
    }];

}


- (void)getDeviceInfo:(CBPeripheral *)peripheral {
    DDLogDebug(@"第五步：获取设备信息");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance writeStormCommand:Command_DeviceInfo ToPeripheral:peripheral Value:nil reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        if (backData.length) {
            DDLogDebug(@"第六步：更新时间");
            [WatchCommandTool.sharedInstance updateDateAndTimeCallBack:^(BOOL success) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                toast(@"链接成功");
//                [self back];
                [self updateUserInfo:peripheral];
            } ToPeripheral:peripheral];
//        }
    }];
}

- (void)updateUserInfo:(CBPeripheral *)peripheral {
    
    NSArray * arr = [[NSUserDefaults standardUserDefaults] valueForKey:@"firstconnectdevices"];
    if (![arr containsObject:peripheral.identifier.UUIDString]) {
        NSMutableArray * mut = [[NSMutableArray alloc] initWithArray:arr];
        [mut addObject:peripheral.identifier.UUIDString];
        [[NSUserDefaults standardUserDefaults] setValue:mut forKey:@"firstconnectdevices"];
       
        [WatchCommandTool.sharedInstance writeStormCommand:Command_SetUserInfo ToPeripheral:peripheral Value:@[@1, @1, @24, @((170 & 0xff00)>>8), @(170 & 0xff), @((70 & 0xff00)>>8), @(70 & 0xff),] reBack:^(NSString * _Nonnull backData) {
            [self back];
        }];
    }else {
        [self back];
    }
}

- (NSMutableArray<CBPeripheral *> *)ScanDataArr {
    if (!_ScanDataArr) {
        _ScanDataArr = [[NSMutableArray alloc] init];
    }
    return _ScanDataArr;
}

- (NSArray *)convertDataToArray:(NSData *)data {
    if (!data || [data length] == 0) {
        return nil;
    }
    NSMutableArray *stringArray = [[NSMutableArray alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [stringArray addObject:hexStr];
            } else {
                [stringArray addObject:[NSString stringWithFormat:@"0%@", hexStr]];
            }
        }
    }];
    
    return stringArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
